﻿using System;
using System.Collections.Generic;
using System.Collections;

using System.Linq;

using System.Text;
using System.Xml;
using System.Data.Linq.SqlClient;
using TaobaoPick.util;


namespace TaobaoPick.storage
{
    public class ItemManager
    {
        ImageSpool imgSpool = new ImageSpool();

        public int updateSite(XmlDocument doc)
        {
            XmlNodeList list = doc.GetElementsByTagName("list-item");
            MyTaobao1DataContext context = LinqAgent.getTaobaoContext();
            int c = 0;
            foreach (XmlNode node in list)
            {
                XmlNodeList nls = node.ChildNodes;
                if (nls.Count == 0)
                    continue;
                XmlNode storeName = node.SelectSingleNode("storeName");
                XmlNode isTmall = node.SelectSingleNode("isTmall");
                if (storeName == null)
                    continue;
                String storeNameStr=storeName.InnerText;

                String site = "taobao";
                if (isTmall != null)
                {
                    if ("true".Equals(isTmall.InnerText))
                        site = "tmall";
                }
                c+=context.ExecuteCommand("update ItemBrief set site={0} where storeName={1}",site,storeNameStr);
                String storeType = "C2C";
                if ("tmall".Equals(site))
                {
                    if (storeNameStr.Contains("专营店") || storeNameStr.Contains("專營店"))
                    {
                        storeType = "專營店";
                    }else
                    if (storeNameStr.Contains("专卖店") || storeNameStr.Contains("專賣店"))
                    {
                        storeType = "專賣店";
                    }
                    else
                    if (storeNameStr.Contains("旗舰店") || storeNameStr.Contains("旗艦店"))
                    {
                      storeType = "旗艦店";
                     }
                        else
                        {
                            storeType = "未歸類";
                        }
                };

                c += context.ExecuteCommand("update ItemBrief set storeType= {0}  where storeName= {1}",storeType, storeNameStr );
                context.SubmitChanges();
            }
            return c;
        }

        public int processItems(XmlDocument doc, DateTime processTime)
        {
            int cc = 0;
            XmlNodeList list = doc.GetElementsByTagName("list-item");
            int total = list.Count;
            foreach (XmlNode node in list)
            {
                if (processItem(node, processTime))
                    cc++;
            }
            return cc;
        }

        public bool processItem(XmlNode node,DateTime processTime)
        {
            XmlNodeList nls = node.ChildNodes;
            if (nls.Count == 0)
                return false;
            XmlNode title = node.SelectSingleNode("title");
            XmlNode img = node.SelectSingleNode("img");
            XmlNode localImgFile = node.SelectSingleNode("localImgFile");
            XmlNode id_by_antispam = node.SelectSingleNode("id_by_antispam");
            XmlNode id = node.SelectSingleNode("id");
            XmlNode logUrl = node.SelectSingleNode("logUrl");
            XmlNode itemUrl = node.SelectSingleNode("itemUrl");
            XmlNode recentSale = node.SelectSingleNode("recentSale");
            XmlNode reviews = node.SelectSingleNode("reviews");
            XmlNode place = node.SelectSingleNode("place");
            XmlNode price = node.SelectSingleNode("price");
            XmlNode isTmall = node.SelectSingleNode("isTmall");
            XmlNode storeName = node.SelectSingleNode("storeName");
            XmlNode storeURLClick = node.SelectSingleNode("storeURLClick");

            XmlNode thumbIdNode = node.SelectSingleNode("thumbId");

            
            //找原本的Item .. if 有..則找最後的一次..,如果沒改內容..
            String itemId = null;
            if (id != null)
            {
                itemId = id.InnerText;
            }
            if (itemId == null)
            {
                if (id_by_antispam == null)
                    return false;
                itemId = id_by_antispam.InnerText;
            }
            //--------------->目前這樣就可以找到了
            //

            MyTaobao1DataContext context=LinqAgent.getTaobaoContext();


            

            //先取出Image的local 跟src
            String srcImageUrl = null;
            String localImageFileName = null;
            if (img != null)
            {
                if (localImgFile != null)
                    localImageFileName = localImgFile.InnerText;
                srcImageUrl = img.InnerText;
            }

            ItemBrief ibf= (from itembrief in context.ItemBriefs where itembrief.ItemId == itemId select itembrief).FirstOrDefault();

            if (ibf == null)
            {
                ItemBrief newItem = new ItemBrief();

                newItem.ItemId = itemId;

                //建立新項目 
                //System.Collections.ArrayList ps=new  System.Collections.ArrayList();
                //String insertSQL ="INSERT INTO ItemBrief  (uid,ItemId, title, site, firstUpdate, lastUpdate, valid, thumbId, realURL, logURL, recentSale, reviews, place1, place2, storeName, price, storeURLClick) VALUES  (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";


                newItem.uid = NewGUID.create("itbf");
                if(title!=null)
                    newItem.title = title.InnerText;

                if (isTmall != null)
                {
                    if ("true".Equals(isTmall.InnerText))
                    {
                        newItem.site = "tmall";
                    }
                    else
                    {
                        newItem.site = "taobao";
                    }
                 }
                else
                    newItem.site = "taobao";

                newItem.firstUpdate = processTime;
                newItem.lastUpdate = processTime;
                newItem.valid = true;


                if (thumbIdNode != null)
                {
                    Guid thumbId = Guid.Parse(thumbIdNode.InnerText);
                    newItem.thumbId = thumbId;
                }
                else
                {
                    Guid thumbId = Guid.Empty;
                    if ((srcImageUrl != null) && (localImageFileName != null))
                    {
                        thumbId = imgSpool.createImageItem(srcImageUrl, localImageFileName);
                    }
                    newItem.thumbId = thumbId;
                }
                
                
                

                //realURL
                if (itemUrl != null)
                   newItem.realURL=itemUrl.InnerText;

                //logURL
                if(logUrl!=null)
                   newItem.logURL=logUrl.InnerText;
                
                //recentSale
                newItem.recentSale = 0;
                if (recentSale != null)
                {
                    int num1;
                    bool res = int.TryParse(recentSale.InnerText, out num1);
                    if (res)
                        newItem.recentSale=num1;
                }

                newItem.reviews = 0;
                if (reviews != null)
                {
                    int num1;
                    bool res = int.TryParse(reviews.InnerText, out num1);
                    if (res)
                        newItem.reviews=num1;
                }
                //------------------------------
                // place1, place2, storeName, price, storeURLClick
                newItem.place1 = "";
                newItem.place2 = "";                        
                if (place != null)
                {
                    String placeStr = place.InnerText.Trim();
                    String[] places = placeStr.Split(' ');
                    if (places.Length >= 1)
                    {
                        newItem.place1 = places[0];                        
                    }
                    if (places.Length >= 2)
                    {
                        newItem.place2 = places[1];
                    }
                }

                // price, storeURLClick
                if (storeName != null)
                {
                    newItem.storeName=storeName.InnerText;
                }else
                    newItem.storeName = "N/A";

                    
                // price, storeURLClick
                newItem.price = new decimal(0);
                if (price != null)
                {
                    decimal l_price = new decimal(0);
                    if(decimal.TryParse(price.InnerText, out l_price))
                        newItem.price = l_price;
                }
                    


                // storeURLClick
                if (storeURLClick != null)
                {
                  newItem.storeURLClick=storeURLClick.InnerText;
                }

                newItem.recentSaleTotal = newItem.price * newItem.recentSale;

                context.ItemBriefs.InsertOnSubmit(newItem);
                 context.SubmitChanges();
              //產生一個ItemLogs
                 ItemLog itemLog = new ItemLog();
                 itemLog.id = NewGUID.create("itlg");
                 itemLog.itemUId = newItem.uid;
                 itemLog.update = processTime;
                 itemLog.reviews = newItem.reviews;
                 itemLog.price = newItem.price;
                
                 itemLog.recentSale = newItem.recentSale;
                 context.ItemLogs.InsertOnSubmit(itemLog);
                 context.SubmitChanges();
            }
            else
            {
                //根據這個時間,增加一筆 log .
                ItemLog itemLog = (from il in context.ItemLogs where il.itemUId == ibf.uid && SqlMethods.DateDiffSecond(il.update, processTime) <100  select il).FirstOrDefault();
                if (itemLog == null)
                {
                    //做一筆新的紀錄
                    itemLog =  new ItemLog();
                    itemLog.id = NewGUID.create("itlg");
                    itemLog.itemUId = ibf.uid;
                    itemLog.update = processTime;

                    if (reviews != null)
                    {
                        int num1=0;
                        bool res = int.TryParse(reviews.InnerText, out num1);
                        if (res)
                            itemLog.reviews = num1;
                    }


                    itemLog.price = new decimal(0);
                    if (price != null)
                    {
                        decimal l_price = new decimal(0);
                        if (decimal.TryParse(price.InnerText, out l_price))
                        {
                            itemLog.price = l_price;
                            ibf.price = l_price;
                        }
                    }

                    itemLog.recentSale = 0;
                    if (recentSale != null)
                    {
                        int num1=0;
                        bool res = int.TryParse(recentSale.InnerText, out num1);
                        if (res)
                        {
                            itemLog.recentSale = num1;
                            ibf.recentSale = num1;
                        }
                    }
                    ibf.recentSaleTotal = ibf.price * ibf.recentSale;
                    context.ItemLogs.InsertOnSubmit(itemLog);
                    context.SubmitChanges();
                }
            }
            return true;

        }


    }
}
